package splug.cjk;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;

import splug.cjk.packet.FriendPacket;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class FriendAdd extends Activity {

	private EditText text_ID;
	private String id;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.friend_add);
		setTitle("친구 요청");

		Bundle b = this.getIntent().getExtras();
		id = b.getString("ID");

		text_ID = (EditText) findViewById(R.id.text_add_friend);
		Button btn_ok = (Button) findViewById(R.id.btn_add_friend_ok);
		Button btn_cancel = (Button) findViewById(R.id.btn_add_friend_cancel);

		btn_ok.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				String str = text_ID.getText().toString();

				//내 아이디가 친구요청 아이디와 같으면 예외처리 한다
				if(id.equals(str)){
					Toast.makeText(FriendAdd.this, "자기 자신을 입력할 수 없습니다.", Toast.LENGTH_SHORT).show();
				}

				//친구 요청 패킷을 보낸다
				else{
					try {
						Socket socket = new Socket(LetsGoActivity.server_ip, 2007);

						InputStream is = socket.getInputStream();
						OutputStream os = socket.getOutputStream();

						OutputStreamWriter osw = new OutputStreamWriter(os);
						InputStreamReader isr = new InputStreamReader(is);

						osw.write(16);
						osw.flush();

						int ack = isr.read(); 

						if(ack == '1'){
							FriendPacket packet = new FriendPacket(null, id, str);
							ObjectOutputStream output = new ObjectOutputStream(os);
							output.writeObject(packet);

							ack = isr.read();

							if(ack == '1'){

								Toast.makeText(FriendAdd.this, "친구 요청 완료!", Toast.LENGTH_SHORT).show();
								finish();
							}
							else if(ack == '0'){
								Toast.makeText(FriendAdd.this, "해당하는 회원을 찾을 수 없습니다", Toast.LENGTH_SHORT).show();
							}
							else if(ack == '2'){
								Toast.makeText(FriendAdd.this, "이미 친구 요청을 하였습니다", Toast.LENGTH_SHORT).show();
							}
						}
						else{
							Toast.makeText(FriendAdd.this, "네트워크 연결상대가 좋지 않습니다", Toast.LENGTH_SHORT).show();
						}


					} catch (UnknownHostException e) {
						e.printStackTrace();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}

			}
		});

		btn_cancel.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();
			}
		});
	}

}
